package com.yao.component;

import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Component
public class LoginHandlerInterceptor implements HandlerInterceptor {

	//在请求处理之前进行调用（Controller方法调用之前）
	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
			throws Exception {
		//统一拦截（查询当前session是否存在user）(这里user会在每次登陆成功后，写入session)
		Object user = request.getSession().getAttribute("username");
		System.out.println("preHandle----"+ user +" ::: "+ request.getRequestURL());
		if(user==null) {
			//request.setAttribute("msg","请先登录！");
			//获取request返回页面到登录页
			request.getRequestDispatcher("/login").forward(request,response);
			//如果设置为false时，被请求时，拦截器执行到此处将不会继续操作
            //如果设置为true时，请求将会继续执行后面的操作
			return false;
		}
		return true;
	}


	//请求处理之后进行调用，但是在视图被渲染之前（Controller方法调用之后）
	@Override
	public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
			ModelAndView modelAndView) {
		Object user = request.getSession().getAttribute("userName");
		System.out.println("postHandle----"+ user +" ::: "+ request.getRequestURL());

	}


	//在整个请求结束之后被调用，也就是在DispatcherServlet 渲染了对应的视图之后执行（主要是用于进行资源清理工作）
	@Override
	public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) {
		Object user = request.getSession().getAttribute("userName");
		System.out.println("afterCompletion----"+ user +" ::: "+ request.getRequestURL());
	}

}
